<template>
  <div style="padding: 20px">
    <!-- 欢迎信息卡片 -->
    <div class="welcome-card">
      <div class="welcome-content">
        <div class="welcome-title">欢迎回来，{{ data.user.username || data.user.name || '用户' }}</div>
        <div class="welcome-subtitle">祝您今天工作顺利，万事如意！</div>
      </div>
      <div class="welcome-date">
        <div class="date-display">{{ currentDate }}</div>
        <div class="time-display">{{ currentTime }}</div>
      </div>
    </div>


    <!-- 快捷入口和最近活动 -->
    <el-row :gutter="20">
      <!-- 快捷入口 -->
      <el-col :span="12">
        <div class="home-card">
          <h3 class="card-title">快捷入口</h3>
          <div class="shortcut-grid">
            <div class="shortcut-item" @click="navigateTo('/projects')">
              <el-icon><Folder /></el-icon>
              <span>项目管理</span>
            </div>
            <div class="shortcut-item" @click="navigateTo('/person')">
              <el-icon><UserFilled /></el-icon>
              <span>个人信息</span>
            </div>
            <div class="shortcut-item" @click="navigateTo('/password')">
              <el-icon><Lock /></el-icon>
              <span>修改密码</span>
            </div>
            <div class="shortcut-item" @click="logout">
              <el-icon><SwitchButton /></el-icon>
              <span>退出系统</span>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 通知 -->
      <el-col :span="12">
        <div class="home-card">
          <h3 class="card-title">通知</h3>
          <div class="activity-list">
            <div v-for="notification in notifications" :key="notification.time" class="activity-item">
              <div class="activity-icon" :style="{ background: getNotificationIconStyle(notification).bg, color: getNotificationIconStyle(notification).color }">
                <el-icon><component :is="getNotificationIconStyle(notification).icon" /></el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-text">
                  <strong>{{ notification.title }}</strong>
                  <div v-if="notification.description" class="notification-description">{{ notification.description }}</div>
                  <div v-if="notification.taskId" class="notification-details">
                    <el-tag size="small" type="info">#{{ notification.taskId }}</el-tag>
                    <el-tag v-if="notification.status" size="small" type="success" style="margin-left: 5px">{{ notification.status === 'completed' ? '已完成' : notification.status }}</el-tag>
                  </div>
                </div>
                <div class="activity-time">{{ formatTime(notification.time) }}</div>
              </div>
            </div>
            <div v-if="notifications.length === 0" class="empty-activity">
              <el-empty description="暂无通知" />
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 待办任务 -->
    <div class="home-card" style="margin-top: 20px">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px">
        <h3 class="card-title" style="margin: 0">我的任务</h3>
        <el-button type="primary" size="small" @click="navigateTo('/projects')">
          查看项目
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      <el-table :data="todoTasks" style="width: 100%" v-if="todoTasks.length > 0">
        <el-table-column prop="title" label="任务名称" min-width="200">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-tag size="small" :type="getTaskTypeTag(row.type)" style="margin-right: 8px">{{ row.type }}</el-tag>
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="project" label="所属项目" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getStatusTag(row.status || 'pending')">
              {{ getStatusText(row.status || 'pending') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="getPriorityTag(row.priority)">{{ row.priority }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="截止日期" width="120">
          <template #default="{ row }">
            <span :class="{ 'overdue-date': isOverdue(row.dueDate) }">{{ row.dueDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewTaskDetail(row)">查看</el-button>
            <el-button type="success" link @click="completeTask(row)">完成</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="empty-tasks">
        <el-empty description="暂无我的任务" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted, defineEmits } from "vue";
import { useRouter } from "vue-router";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { getAllWorkItems, getWorkItemsByResponsiblePerson, updateWorkItem } from "@/api/workitem";
import { getAllProjects, getProjectById } from "@/api/project";

const router = useRouter();

// 用户数据
const data = reactive({
  user: (() => {
    try {
      return JSON.parse(localStorage.getItem('system-user') || '{}');
    } catch (error) {
      console.error('JSON解析失败:', error);
      ElMessage.error('数据解析失败，请联系管理员');
      return {};
    }
  })()
});

// 当前日期和时间
const currentDate = computed(() => {
  const now = new Date();
  return now.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });
});

const currentTime = computed(() => {
  const now = new Date();
  return now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
});

// 统计数据
const stats = reactive({
  projects: 5,
  tasks: 8,
  teams: 3,
  notifications: 2
});

// 通知数据
const notifications = ref([]);

// 从本地存储加载通知
const loadNotifications = () => {
  try {
    const savedNotifications = JSON.parse(localStorage.getItem('notifications') || '[]');
    notifications.value = savedNotifications;
    // 更新统计数据中的未读通知数
    stats.notifications = savedNotifications.filter(n => !n.read).length;
  } catch (error) {
    console.error('加载通知失败:', error);
  }
};

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  const now = new Date();
  const diff = now - date;
  
  // 如果是今天的通知，显示"今天 HH:MM"
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return `今天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
  }
  
  // 如果是昨天的通知，显示"昨天 HH:MM"
  if (diff < 48 * 60 * 60 * 1000 && date.getDate() === now.getDate() - 1) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`;
  }
  
  // 其他情况显示完整日期时间
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取通知图标样式
const getNotificationIconStyle = (notification) => {
  // 根据通知类型或内容返回不同的图标和样式
  if (notification.status === 'completed') {
    return {
      icon: 'Check',
      bg: '#f6ffed',
      color: '#52c41a'
    };
  } else if (notification.taskId) {
    return {
      icon: 'Document',
      bg: '#e6f7ff',
      color: '#1890ff'
    };
  } else {
    return {
      icon: 'Bell',
      bg: '#fff7e6',
      color: '#fa8c16'
    };
  }
};

// 待办任务
const todoTasks = ref([]);

// 项目ID到项目名称的映射
const projectMap = ref({});

// 加载项目列表并构建映射
const loadProjects = async () => {
  try {
    const response = await getAllProjects();
    if (response.code === '200' && response.data) {
      // 构建项目ID到项目名称的映射
      const projects = response.data;
      projects.forEach(project => {
        projectMap.value[project.projectId] = project.projectName;
      });
      console.log('项目映射:', projectMap.value);
    } else {
      console.error('获取项目列表失败:', response.msg);
    }
  } catch (error) {
    console.error('加载项目列表失败:', error);
  }
};

// 加载待办任务
const loadTodoTasks = async () => {
  try {
    // 获取当前用户负责的工作项
    const currentUser = data.user.username;
    if (!currentUser) {
      console.error('未找到当前用户信息');
      return;
    }
    
    console.log('当前用户:', currentUser);
    const response = await getWorkItemsByResponsiblePerson(currentUser);
    
    if (response.code === '200' && response.data) {
      console.log('获取到的用户工作项数据:', response.data);
      // 将后端工作项数据转换为前端显示格式
      
      todoTasks.value = response.data.map(item => {
        console.log('工作项数据:', item);
        return {
          id: item.workItemId,
          title: item.title,
          project: item.projectId ? (projectMap.value[item.projectId] || `项目 #${item.projectId}`) : '未分配项目',
          type: item.category || '任务',
          priority: item.priority || '中',
          dueDate: item.end_time ? new Date(item.end_time).toLocaleDateString() : '无截止日期',
          status: item.status,
          description: item.description,
          responsiblePerson: item.responsiblePerson
        };
      });
      
      // 打印转换后的待办任务数据
      console.log('转换后的待办任务:', todoTasks.value);
      
      // 更新统计数据中的待办任务数
      stats.tasks = todoTasks.value.length;
    } else {
      console.error('获取待办任务失败:', response.msg);
      ElMessage.warning('获取待办任务失败: ' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('加载待办任务失败:', error);
    ElMessage.warning('加载待办任务失败');
  }
};

// 方法
const navigateTo = (path) => {
  router.push(path);
};

const logout = () => {
  ElMessage.success('退出成功');
  localStorage.removeItem('system-user');
  router.push('/login');
};

const getTaskTypeTag = (type) => {
  const types = {
    '开发': 'primary',
    '设计': 'success',
    '测试': 'warning',
    '文档': 'info',
    '缺陷': 'danger',
    '任务': 'info',
    'bug': 'danger',
    'feature': 'primary',
    'story': 'success'
  };
  return types[type] || 'info';
};

const getPriorityTag = (priority) => {
  const priorities = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info',
    'high': 'danger',
    'medium': 'warning',
    'low': 'info'
  };
  return priorities[priority] || 'info';
};

const getStatusTag = (status) => {
  const statusMap = {
    'pending': 'info',
    'in_progress': 'warning',
    'completed': 'success',
    'cancelled': 'danger',
    'paused': 'warning',
    'active': 'primary'
  };
  return statusMap[status] || 'info';
};

const getStatusText = (status) => {
  const statusTextMap = {
    'pending': '待处理',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消',
    'paused': '已暂停',
    'active': '活跃'
  };
  return statusTextMap[status] || status;
};

const isOverdue = (dateStr) => {
  const dueDate = new Date(dateStr);
  const today = new Date();
  return dueDate < today;
};

const viewTaskDetail = (task) => {
  // 如果任务属于某个项目，跳转到项目任务详情页
  if (task.project && task.project.includes('#')) {
    const projectId = task.project.split('#')[1];
    router.push(`/projects/${projectId}?taskId=${task.id}`);
  } else {
    // 否则只显示消息
    ElMessage.info(`查看任务详情: ${task.title}`);
    // 可以在这里显示一个包含任务详情的对话框
  }
};

const completeTask = async (task) => {
  try {
    // 调用API更新任务状态为已完成
    const response = await updateWorkItem(task.id, {
      workItemId: task.id,
      status: 'completed'
    });
    
    if (response.code === '200') {
      ElMessage.success(`任务已完成: ${task.title}`);
      // 重新加载待办任务
      loadTodoTasks();
    } else {
      ElMessage.error(response.msg || '更新任务状态失败');
    }
  } catch (error) {
    console.error('完成任务失败:', error);
    ElMessage.error('完成任务失败，请稍后重试');
  }
};

// 定义事件
const emit = defineEmits(['updateUser'])

// 更新用户信息的方法
const updateUserInfo = () => {
  try {
    const userData = localStorage.getItem('system-user');
    if (userData) {
      data.user = JSON.parse(userData);
    }
  } catch (error) {
    console.error('JSON解析失败:', error);
  }
}

// 获取数据
onMounted(async () => {
  // 获取用户信息
  updateUserInfo();
  
  // 监听storage事件，当localStorage变化时更新用户信息
  window.addEventListener('storage', (e) => {
    if (e.key === 'system-user') {
      updateUserInfo();
    }
  })
  
  // 先加载项目列表
  await loadProjects();
  
  // 加载通知数据
  loadNotifications();
  
  // 加载待办任务数据
  loadTodoTasks();
});
</script>

<style scoped>
.welcome-card {
  background: linear-gradient(135deg, #1890ff, #722ed1);
  border-radius: 8px;
  padding: 24px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.welcome-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.welcome-subtitle {
  font-size: 16px;
  opacity: 0.9;
}

.welcome-date {
  text-align: right;
}

.date-display {
  font-size: 16px;
  margin-bottom: 4px;
}

.time-display {
  font-size: 24px;
  font-weight: bold;
}

.stat-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.home-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.card-title {
  font-size: 18px;
  color: #333;
  margin-top: 0;
  margin-bottom: 20px;
  font-weight: 600;
}

.shortcut-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.shortcut-item {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.shortcut-item:hover {
  background-color: #e6f7ff;
  transform: translateY(-3px);
}

.shortcut-item .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #1890ff;
}

.shortcut-item span {
  font-size: 14px;
  color: #333;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 300px; /* 设置最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
  padding-right: 5px; /* 添加右侧内边距，避免滚动条贴边 */
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: #dcdfe6 #f2f6fc; /* Firefox */
}

/* 自定义滚动条样式 - Webkit浏览器 */
.activity-list::-webkit-scrollbar {
  width: 6px;
}

.activity-list::-webkit-scrollbar-track {
  background: #f2f6fc;
  border-radius: 3px;
}

.activity-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
  transition: all 0.3s;
}

.activity-list::-webkit-scrollbar-thumb:hover {
  background-color: #c0c4cc;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.activity-item:hover {
  background-color: #f5f7fa;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.activity-target {
  color: #1890ff;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

.notification-description {
  font-size: 13px;
  color: #666;
  margin-top: 4px;
  line-height: 1.5;
}

.notification-details {
  margin-top: 6px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

.empty-activity,
.empty-tasks {
  padding: 20px 0;
}

.overdue-date {
  color: #f5222d;
  font-weight: bold;
}
</style>